package com.example.controller;

import com.example.Utils.DingText;
import com.example.pojo.Result;
import com.example.pojo.meetingRoomPojo;
import com.example.service.meetingRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class meetingRoomController {

    @Autowired
    private meetingRoomService meetingRoomService;

    // 第一个钉钉机器人配置
    private static final String DINGTALK_WEBHOOK_1 = "https://oapi.dingtalk.com/robot/send?access_token=37cde492877f00e02942e949a0416698a704512c5a2c26dfd5393be05529fb35";
    private static final String DINGTALK_SECRET_1 = "SECc7e84985023158784dca774d8d2b612bdd5d412fea4a14b9d9d66480708e13b8";

    // 第二个钉钉机器人配置
    private static final String DINGTALK_WEBHOOK_2 = "https://oapi.dingtalk.com/robot/send?access_token=405a13cca8ed3752fbed2669c33835f81cdc467d1e1d694bb747da0bcd0df1e4";
    private static final String DINGTALK_SECRET_2 = null; // 设置为null而不是空字符串

    @PostMapping("/queryMeetingRoom")
    public Result queryMeetingRoom(){
        List<meetingRoomPojo> meetingRoomList = meetingRoomService.queryAll();
        System.out.println("meeting查询成功");
        return Result.success(meetingRoomList);
    }

    @PostMapping("/addMeetingRoom")
    public Result addMeetingRoom(@RequestBody meetingRoomPojo meetingRoomPojo){
        // 强制生成ID
        generateMeetingRoomId(meetingRoomPojo);
        System.out.println(meetingRoomPojo);
        meetingRoomService.insertOne(meetingRoomPojo);
        System.out.println("meeting添加成功");

        // 发送钉钉通知到两个机器人
        sendMeetingRoomNotification("添加", meetingRoomPojo);

        return Result.success();
    }

    @PostMapping("/editMeetingRoom")
    public Result editMeetingRoom(@RequestBody meetingRoomPojo meetingRoomPojo){
        meetingRoomService.updateMeetingRoom(meetingRoomPojo);
        System.out.println("meeting修改成功");

        // 发送钉钉通知到两个机器人
        sendMeetingRoomNotification("修改", meetingRoomPojo);

        return Result.success("meeting修改成功");
    }

    @PostMapping("/saveMeetingRoom")
    public Result saveMeetingRoom(@RequestBody meetingRoomPojo meetingRoomPojo){
        System.out.println("保存会议室数据: " + meetingRoomPojo);

        try {
            // 更严格的ID检查
            if (meetingRoomPojo.getId() == null ||
                    meetingRoomPojo.getId().trim().isEmpty() ||
                    meetingRoomPojo.getId().equals("")) {

                // 新增 - 强制生成ID
                generateMeetingRoomId(meetingRoomPojo);
                meetingRoomService.insertOne(meetingRoomPojo);
                System.out.println("meeting添加成功，生成的ID: " + meetingRoomPojo.getId());

                // 发送钉钉通知到两个机器人
                sendMeetingRoomNotification("添加", meetingRoomPojo);

                return Result.success("meeting添加成功");
            } else {
                // 更新
                meetingRoomService.updateMeetingRoom(meetingRoomPojo);
                System.out.println("meeting修改成功");

                // 发送钉钉通知到两个机器人
                sendMeetingRoomNotification("修改", meetingRoomPojo);

                return Result.success("meeting修改成功");
            }
        } catch (Exception e) {
            System.err.println("保存会议室数据失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "保存失败: " + e.getMessage());
        }
    }

    /**
     * 生成会议室ID并设置到对象中
     */
    private void generateMeetingRoomId(meetingRoomPojo meetingRoomPojo) {
        String newId = "MR_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
        meetingRoomPojo.setId(newId);
        System.out.println("生成的会议室ID: " + newId);
    }

    @PostMapping("/deleteMeetingRoom")
    public Result deleteMeetingRoom(@RequestBody meetingRoomPojo meetingRoomPojo) {
        try {
            if (meetingRoomPojo.getId() == null || meetingRoomPojo.getId().trim().isEmpty()) {
                return Result.error(400, "ID不能为空");
            }
            meetingRoomService.deleteMeetingRoom(meetingRoomPojo.getId());
            System.out.println("meeting删除成功，ID: " + meetingRoomPojo.getId());

            // 发送钉钉通知到两个机器人
            sendMeetingRoomNotification("删除", meetingRoomPojo);

            return Result.success("meeting删除成功");
        } catch (Exception e) {
            System.err.println("删除会议室数据失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error(500, "删除失败: " + e.getMessage());
        }
    }

    /**
     * 发送会议室操作通知到两个钉钉机器人
     * 只包含 creator, meetingRoomData, meetingRoomTime, meetingRoomTopic
     */
    private void sendMeetingRoomNotification(String operationType, meetingRoomPojo meetingRoom) {
        try {
            // 构建消息内容 - 只包含要求的四个字段
            StringBuilder message = new StringBuilder();
            message.append("📋 MeetingRoom").append(operationType).append("Notification\n");
            message.append("---------------------------------------\n");

            // 只添加要求的四个字段
            if (meetingRoom.getCreator() != null && !meetingRoom.getCreator().trim().isEmpty()) {
                message.append("👤Booker : ").append(meetingRoom.getCreator()).append("\n");
                message.append("---------------------------------------\n");
            }

            if (meetingRoom.getMeetingRoomData() != null && !meetingRoom.getMeetingRoomData().trim().isEmpty()) {
                message.append("📅 Meeting Data: ").append(meetingRoom.getMeetingRoomData()).append("\n");
                message.append("---------------------------------------\n");
            }

            if (meetingRoom.getMeetingRoomTime() != null && !meetingRoom.getMeetingRoomTime().trim().isEmpty()) {
                message.append("⏰ Time: ").append(meetingRoom.getMeetingRoomTime()).append("\n");
                message.append("---------------------------------------\n");
            }

            if (meetingRoom.getMeetingRoomTopic() != null && !meetingRoom.getMeetingRoomTopic().trim().isEmpty()) {
                message.append("💬 Topic: ").append(meetingRoom.getMeetingRoomTopic()).append("\n");
                message.append("---------------------------------------\n");
            }

            // 发送到第一个钉钉机器人
            try {
                DingText.sendMessageByText(
                        message.toString(),
                        new ArrayList<>(), // 空列表，不@任何人
                        false,
                        DINGTALK_SECRET_1,
                        DINGTALK_WEBHOOK_1
                );
                System.out.println("第一个钉钉通知发送成功: " + operationType + "会议室");
            } catch (Exception e) {
                System.err.println("发送第一个钉钉通知失败: " + e.getMessage());
            }

            // 发送到第二个钉钉机器人
            try {
                DingText.sendMessageByText(
                        message.toString(),
                        new ArrayList<>(), // 空列表，不@任何人
                        false,
                        DINGTALK_SECRET_2, // 设置为null
                        DINGTALK_WEBHOOK_2
                );
                System.out.println("第二个钉钉通知发送成功: " + operationType + "会议室");
            } catch (Exception e) {
                System.err.println("发送第二个钉钉通知失败: " + e.getMessage());
            }

        } catch (Exception e) {
            System.err.println("发送钉钉通知失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
